// TcpClient.cc文件
#include <iostream>
#include "Common.hpp"
#include "InetAddr.hpp"
#include <unistd.h>

// Usage: ./tcpclient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        exit(ExitCode::USAGE_ERR);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);
    // 1.创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "创建socket失败" << std::endl;
        exit(ExitCode::SOCKET_ERR);
    }
    // 2.直接向目标服务器发起建立连接的请求
    InetAddr client(server_ip, server_port); // 这里要主机转网络
    int n = connect(sockfd, client.NetAddrPtr(), client.NetAddrLen());
    if (n < 0)
    {
        std::cout << "connect error" << std::endl;
        exit(ExitCode::CONNECT_ERR);
    }

    while (true)
    {
        // 3.发消息
        std::cout << "Please Enter# ";
        std::string line;
        std::getline(std::cin, line);
        write(sockfd, line.c_str(), line.size());
        // 4.收消息
        char buffer[1024];
        ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }
    close(sockfd);
    return 0;
}
